package system.imp;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import system.until.ImageZipUtil;

import com.hitrust.gs.dao.GSManufactureDAO;
import com.hitrust.gs.lib.GSSystemConfigurator;

public class ProductPictureShowServlet extends javax.servlet.http.HttpServlet {
	private static final String GIF = "image/gif;charset=GB2312";
	private static final String JPG = "image/jpeg;charset=GB2312";
	private static final String BMP = "image/bmp;charset=GB2312";
	private static final String PNG = "image/png;charset=GB2312";

	public ProductPictureShowServlet() {
		super();
	}

	public void init() throws ServletException {
	}

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws javax.servlet.ServletException, java.io.IOException {
		String type = (String) request.getParameter("type");
		if (type != null && "1".equals(type)) {
			performTaskByFile(request, response);
		} else if (type != null && "2".equals(type)) {
			deletePicture(request, response);
		} else if (type != null && "3".equals(type)) {
			getPicture(request, response);
		} else {
			performTask(request, response);
		}

	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws javax.servlet.ServletException, java.io.IOException {

	}

	/**  
  *   
  */
	private static final long serialVersionUID = 7440302204266787092L;

	public void performTask(HttpServletRequest request,
			HttpServletResponse response) throws IOException, ServletException {
		try {
			String productCode = (String) request.getParameter("productCode");
			String path=GSSystemConfigurator.getParam("gs.pic.filePath");
			String imagePath = path + productCode + "/";
			String fileName = getMinFile(imagePath);
			String imagePathAll = imagePath + fileName;
			String smallPicPath = path +"smallPic/";
			String smallImagePath = path +"smallPic/"+productCode+"/";
			String smallFilePath = path +"smallPic/"+productCode+"/"+ fileName;
			response.reset();
			OutputStream output = response.getOutputStream();
			if (fileName != null && fileName.toLowerCase().endsWith(".jpg")) {
				response.setContentType(JPG);
				String returnInfo=ImageZipUtil.zipImageFileDif(imagePathAll, 512, 384, 1f,smallPicPath,smallImagePath,smallFilePath);
				InputStream imageIn=null;
				if("pictureCanNotRead".equals(returnInfo)){
					 imageIn = new FileInputStream(
								new File(imagePathAll));
				}else{
					 imageIn = new FileInputStream(
							new File(smallFilePath));
				}
			
				BufferedInputStream bis = new BufferedInputStream(imageIn);
				BufferedOutputStream bos = new BufferedOutputStream(output);
				byte data[] = new byte[4096];
				int size = 0;
				size = bis.read(data);
				while (size != -1) {
					bos.write(data, 0, size);
					size = bis.read(data);
				}
				bis.close();
				bos.flush();
				bos.close();
			}

			if (fileName != null && fileName.toLowerCase().endsWith(".gif")) {
				response.setContentType(GIF);
				InputStream imageIn = new FileInputStream(
						new File(imagePathAll));
				BufferedInputStream bis = new BufferedInputStream(imageIn);
				BufferedOutputStream bos = new BufferedOutputStream(output);
				byte data[] = new byte[4096];
				int size = 0;
				size = bis.read(data);
				while (size != -1) {
					bos.write(data, 0, size);
					size = bis.read(data);
				}
				bis.close();
				bos.flush();
				bos.close();
			}
			if (fileName != null && fileName.toLowerCase().endsWith(".bmp")) {
				response.setContentType(BMP);
				InputStream imageIn = new FileInputStream(
						new File(imagePathAll));
				BufferedInputStream bis = new BufferedInputStream(imageIn);
				BufferedOutputStream bos = new BufferedOutputStream(output);
				byte data[] = new byte[4096];
				int size = 0;
				size = bis.read(data);
				while (size != -1) {
					bos.write(data, 0, size);
					size = bis.read(data);
				}
				bis.close();
				bos.flush();
				bos.close();
			}

			if (fileName != null && fileName.toLowerCase().endsWith(".png")) {
				response.setContentType(PNG);
				InputStream imageIn = new FileInputStream(
						new File(imagePathAll));
				BufferedInputStream bis = new BufferedInputStream(imageIn);
				BufferedOutputStream bos = new BufferedOutputStream(output);
				byte data[] = new byte[4096];
				int size = 0;
				size = bis.read(data);
				while (size != -1) {
					bos.write(data, 0, size);
					size = bis.read(data);
				}
				bis.close();
				bos.flush();
				bos.close();
			}
			if (fileName == null||"".equals(fileName)) {
				response.setContentType(GIF);
				String picpath=GSSystemConfigurator.getParam("gs.pic.filePath");
				InputStream imageIn = new FileInputStream(new File(
						picpath+"default.bmp"));
				BufferedInputStream bis = new BufferedInputStream(imageIn);
				BufferedOutputStream bos = new BufferedOutputStream(output);
				byte data[] = new byte[4096];
				int size = 0;
				size = bis.read(data);
				while (size != -1) {
					bos.write(data, 0, size);
					size = bis.read(data);
				}
				bis.close();
				bos.flush();
				bos.close();
			}
			output.close();
		} catch (Exception e) {

		}
	}

	public void performTaskByFile(HttpServletRequest request,
			HttpServletResponse response) throws IOException, ServletException {
		try {
			String productCode = (String) request.getParameter("productCode");
			System.out.println("productCode"+productCode);
			String picpath=GSSystemConfigurator.getParam("gs.pic.filePath");
			String imagePath = picpath + productCode + "/";
			System.out.println("imagePath"+imagePath);
			File file = new File(imagePath);
			String strImage = "{'images':[";
			if (!file.exists()) {
				System.out.println("文件夹不存在!");
				return;
			}
			if (!file.isDirectory()) {
				System.out.println("文件夹不是上级路径");
				return;
			}
			String[] tempList = file.list();

			if (tempList != null) {
				for (int i = 0; i < tempList.length; i++) {
					if (tempList[i].toLowerCase().endsWith(".jpg")
							|| tempList[i].toLowerCase().endsWith(".gif")
							|| tempList[i].toLowerCase().endsWith(".bmp")
							|| tempList[i].toLowerCase().endsWith(".png")) {
						File file2 = new File(imagePath + tempList[i]);

						strImage += "{'name':'" + tempList[i] + "','url':'"
								+ "/gw/servlet/ProductPictureShowServlet?path="
								+ imagePath + tempList[i] + "&type=3"
								+ "','size':'" + file2.length() + "'},";
					}
				}
			}else{
				System.out.println("文件夹下不存在任何文件");
			}
			
			strImage = strImage.substring(0, (strImage.length() - 1));
			strImage += "]}";
			System.out.println("strImage"+strImage);
			response.getWriter().write(strImage);
			response.getWriter().close();
		} catch (Exception e) {

		}
	}

	public void deletePicture(HttpServletRequest request,
			HttpServletResponse response) throws IOException, ServletException {
		String productCode = (String) request.getParameter("productCode");
		String picpath=GSSystemConfigurator.getParam("gs.pic.filePath");
		String imagePath = picpath + productCode + "/";
		String strNodes = request.getParameter("Nodes");
		String[] nodes = strNodes.split(",");
		try {
			for (int i = 0; i < nodes.length; i++) {
				String strPath = imagePath + nodes[i];
				File file = new File(strPath);
				if (!file.exists()) {
					response.getWriter().write("{success:false}");
				}
				if (!file.isDirectory()) {
					response.getWriter().write("{success:false}");
				}
				file.delete();
				File files = new File(imagePath);
				String[] fileArrays=files.list(); 
				if(!files.exists()){
					System.out.println("文件夹不存在!");
				}else{
					if(fileArrays.length==0){
						System.out.println("文件夹内不存在文件!");
					GSManufactureDAO manuDao=new GSManufactureDAO();
					manuDao.delProductPicureByConcentricityCode(productCode);
					//删除T_PRODUCT_PICTURE对应的记录
					}else{
						System.out.println("文件夹内存在文件!");
					}
				}
				response.getWriter().write("{success:true}");
			}
		} catch (Exception e) {
			response.getWriter().write("{success:false}");
		}

	}

	public static String getMinFile(String path) {
		File file = new File(path);
		if (!file.exists()) {
			return null;
		}
		if (!file.isDirectory()) {
			return null;
		}
		String[] tempList = file.list();
		
		int min = 999999;
		String fileName="";
		for (int i = 0; i < tempList.length; i++) {
			if (path.endsWith(File.separator)) {
				if (".jpg".equalsIgnoreCase(tempList[i].substring(
						tempList[i].length() - 4, tempList[i].length()))
						|| ".gif"
								.equalsIgnoreCase(tempList[i].substring(
										tempList[i].length() - 4,
										tempList[i].length()))
						|| ".bmp"
								.equalsIgnoreCase(tempList[i].substring(
										tempList[i].length() - 4,
										tempList[i].length()))
						|| ".png"
								.equalsIgnoreCase(tempList[i].substring(
										tempList[i].length() - 4,
										tempList[i].length()))) {
					String names = tempList[i].substring(0,
							tempList[i].length() - 4);
					if (Integer.parseInt(names) <= min) {
						min = Integer.parseInt(names);
						fileName=tempList[i];
					}

				}
			} else {
				if (".jpg".equalsIgnoreCase(tempList[i].substring(
						tempList[i].length() - 4, tempList[i].length()))
						|| ".gif"
								.equalsIgnoreCase(tempList[i].substring(
										tempList[i].length() - 4,
										tempList[i].length()))
						|| ".bmp"
								.equalsIgnoreCase(tempList[i].substring(
										tempList[i].length() - 4,
										tempList[i].length()))
						|| ".png"
								.equalsIgnoreCase(tempList[i].substring(
										tempList[i].length() - 4,
										tempList[i].length()))) {
					String names = tempList[i].substring(0,
							tempList[i].length() - 4);
					if (Integer.parseInt(names) <= min) {
						min = Integer.parseInt(names);
						fileName=tempList[i];
					}

				}
			}
		}
		return fileName;
	}

	public void getPicture(HttpServletRequest request,
			HttpServletResponse response) throws IOException, ServletException {
		try {
			String imagePathAll = (String) request.getParameter("path");
			response.reset();
			OutputStream output = response.getOutputStream();
			if (imagePathAll != null
					&& imagePathAll.toLowerCase().endsWith(".jpg")) {
				response.setContentType(JPG);
				InputStream imageIn = new FileInputStream(
						new File(imagePathAll));
				BufferedInputStream bis = new BufferedInputStream(imageIn);
				BufferedOutputStream bos = new BufferedOutputStream(output);
				byte data[] = new byte[4096];
				int size = 0;
				size = bis.read(data);
				while (size != -1) {
					bos.write(data, 0, size);
					size = bis.read(data);
				}
				bis.close();
				bos.flush();
				bos.close();
			}

			if (imagePathAll != null
					&& imagePathAll.toLowerCase().endsWith(".gif")) {
				response.setContentType(GIF);
				InputStream imageIn = new FileInputStream(
						new File(imagePathAll));
				BufferedInputStream bis = new BufferedInputStream(imageIn);
				BufferedOutputStream bos = new BufferedOutputStream(output);
				byte data[] = new byte[4096];
				int size = 0;
				size = bis.read(data);
				while (size != -1) {
					bos.write(data, 0, size);
					size = bis.read(data);
				}
				bis.close();
				bos.flush();
				bos.close();
			}
			if (imagePathAll != null
					&& imagePathAll.toLowerCase().endsWith(".bmp")) {
				response.setContentType(BMP);
				InputStream imageIn = new FileInputStream(
						new File(imagePathAll));
				BufferedInputStream bis = new BufferedInputStream(imageIn);
				BufferedOutputStream bos = new BufferedOutputStream(output);
				byte data[] = new byte[4096];
				int size = 0;
				size = bis.read(data);
				while (size != -1) {
					bos.write(data, 0, size);
					size = bis.read(data);
				}
				bis.close();
				bos.flush();
				bos.close();
			}

			if (imagePathAll != null
					&& imagePathAll.toLowerCase().endsWith(".png")) {
				response.setContentType(PNG);
				InputStream imageIn = new FileInputStream(
						new File(imagePathAll));
				BufferedInputStream bis = new BufferedInputStream(imageIn);
				BufferedOutputStream bos = new BufferedOutputStream(output);
				byte data[] = new byte[4096];
				int size = 0;
				size = bis.read(data);
				while (size != -1) {
					bos.write(data, 0, size);
					size = bis.read(data);
				}
				bis.close();
				bos.flush();
				bos.close();
			}
			output.close();
		} catch (Exception e) {

		}
	}

}
